/*
 * @Description: c++存储任意类型，并拥有多种序列化功能
 * @Author: dengzhijun
 * @Date: 2025-01-17 10:13:16
 * @LastEditTime: 2025-02-05 10:05:32
 * @LastEditors: dengzhijun 1726768643@qq.com
 */

#ifndef TOOLS_VARIANT_H
#define TOOLS_VARIANT_H

#include <any>
#include <memory>
#include <string>
#include <map>
#include <list>
#include <type_traits>
#include <ostream>
#include <iostream>
#include <unordered_map>
#include <fstream>
#include <functional>
#include <mutex>
#include <set>
#include <variant>
#include "Global.h"
#include <functional>
#include "Endian.h"

namespace Tool
{

enum class VariantType : uint8_t
{
    None,
    Bool,
    Int,
    UInt,
    Long,
    ULong,
    Float,
    Double,
    String,
    Vector,
    List,
    Set,
    Map,
    Hash,
    Binary,  // 添加二进制类型,std::vector<uint8_t> data 可以存储文件数据
    User
};

enum class VariantSerializeType
{
    Binary,
    Json
};

std::string ExportAPI DemangleTypeName(const char* mangledName);
std::string ExportAPI CleanupTypeName(std::string& typeName);

class Variant;
using VariantMap = std::map<std::string, Variant>;
using VariantSet = std::set<Variant>;
using VariantHash = std::unordered_map<std::string, Variant>;
using VariantList = std::list<Variant>;
using VariantVector = std::vector<Variant>;

//#define DeserializeBinarySize
#ifdef DeserializeBinarySize
typedef uint16_t variant_t;  // 65535
#else
typedef uint32_t variant_t;          // 21亿
#endif


template <VariantType VT>
struct VariantTypeTraits
{
    static_assert(VT != VT, "未定义该 VariantType 对应的 C++ 类型");
};

template <> struct VariantTypeTraits<VariantType::UInt>   { using Type = uint32_t; };
template <> struct VariantTypeTraits<VariantType::Long>   { using Type = int64_t; };
template <> struct VariantTypeTraits<VariantType::Float>  { using Type = float; };
template <> struct VariantTypeTraits<VariantType::Int>    { using Type = int32_t; };
template <> struct VariantTypeTraits<VariantType::ULong>  { using Type = uint64_t; };
template <> struct VariantTypeTraits<VariantType::Double> { using Type = double; };
template <> struct VariantTypeTraits<VariantType::Bool>   { using Type = bool; };

class ExportAPI Variant
{
public:

    //定义 内存char*类型的，转成iostream使用的基类basic_streambuf
    template <typename Tchar>
    class basic_memorybuf : public std::basic_streambuf<Tchar>
    {
    public:
        basic_memorybuf(const Tchar* data, size_t size)
        {
            this->setg(const_cast<Tchar*>(data), const_cast<Tchar*>(data), const_cast<Tchar*>(data) + size);
        }
    };

    Variant();
    ~Variant();
    Variant(bool data);
    Variant(int data);
    Variant(unsigned int data);
    Variant(long long data);
    Variant(unsigned long long data);
    Variant(float data);
    Variant(double data);
    Variant(const char* data);
    Variant(const std::string& data);
    Variant(const std::vector<Variant>& data);
    Variant(const std::list<Variant>& data);
    Variant(const std::set<Variant>& data);
    Variant(const std::map<std::string, Variant> &data);
    Variant(const std::unordered_map<std::string, Variant> &data);
    Variant(const std::initializer_list<Variant> &list);
    Variant(const std::vector<uint8_t>& data);
    Variant(const std::vector<VariantHash>& value);

    Variant(std::string&& data);
    Variant(std::vector<Variant>&& data);
    Variant(std::list<Variant>&& data);
    Variant(std::set<Variant>&& data);
    Variant(std::map<std::string, Variant> &&data);
    Variant(std::unordered_map<std::string, Variant> &&data);
    Variant(std::vector<uint8_t>&& data);
    Variant(const std::vector<VariantHash>&& value);

    Variant(const Variant &data);
    Variant(Variant &&data) noexcept;
    Variant& operator=(Variant data);

    // Variant& operator=(const Variant &data);
    // Variant& operator=(Variant &&data) noexcept;

    template<typename T>
    static Variant FromValue(T t);

    template<typename T>
    T Value() const;

    template<typename T>
    T &RefValue() const;

    template <typename T, typename U>
    T ConvertValue(const U &value) const;

    VariantType Type() const;
    bool ToBool() const;
    int ToInt() const;
    unsigned int ToUInt() const;
    long long ToLong() const;
    unsigned long long ToULong() const;
    float ToFloat() const;
    double ToDouble() const;
    std::string ToString() const;
    std::vector<Variant> ToVector() const;
    std::list<Variant> ToList() const;
    std::set<Variant> ToSet() const;
    std::map<std::string, Variant> ToMap() const;
    std::unordered_map<std::string, Variant> ToHash() const;
    std::vector<uint8_t> ToBinary() const;

    std::string &ToString();
    std::vector<Variant> &ToVector();
    std::list<Variant> &ToList();
    std::set<Variant> &ToSet();
    std::map<std::string, Variant> &ToMap();
    std::unordered_map<std::string, Variant> &ToHash();
    std::vector<uint8_t> &ToBinary();

    //重载隐式类型转换
    operator bool() const;
    operator int() const;
    operator long int() const;
    operator unsigned int() const;
    operator long long() const;
    operator unsigned long long() const;
    operator float() const;
    operator double() const;
    operator std::string() const;
    operator std::vector<Variant>() const;
    operator std::list<Variant>() const;
    operator std::set<Variant>() const;
    operator std::map<std::string, Variant>() const;
    operator std::unordered_map<std::string, Variant>() const;

    operator std::string&();
    operator std::vector<Variant>&();
    operator std::list<Variant>&();
    operator std::set<Variant>&();
    operator std::map<std::string, Variant>&();
    operator std::unordered_map<std::string, Variant>&();
    operator std::vector<uint8_t>() const;
    operator std::vector<uint8_t>&();

    const Variant& operator [](int index) const;
    const Variant& operator [](const std::string &key) const;
    const Variant& operator [](const char *key) const;  

    Variant& operator [](int index);
    Variant& operator [](const std::string &key);
    Variant& operator [](const char *key);

    Variant Get(const std::string& key, const Variant& defaultValue = Variant()) const;
    
    /**
     * @description:  == 禁止在没有key赋值自身 variant["key"] = variant; 这样会先创建一个默认值，然后被赋值variant又被赋值给了新key导致。有一个默认值没被初始化
     * @description:  == 可以在有key的时候赋值，或者在没有key的时候variant["key"] = Variant(variant); 这样会先调用构造函数再进行赋值
     * @return {*}
     */

    bool operator!=(const Variant& other) const;
    bool operator==(const Variant& other) const;
    bool operator<(const Variant& other) const;
    bool operator>(const Variant& other) const;
    bool operator<=(const Variant& other) const;
    bool operator>=(const Variant& other) const;

    bool Contains(const std::string& key) const;
    inline const std::string& GetTypeName() const;
    inline bool IsNull() const;

    /**
     * @description:  输入流和输出流是以json，可以用于显示
     */
    friend ExportAPI std::ostream& operator<<(std::ostream& os, const Tool::Variant& variant);
    // friend ExportAPI std::istream& operator>>(std::istream& is, Tool::Variant& variant);


    // 序列化到文件，文件反序列化 序列化到字符 字符反序列化 序列化到json json反序列化 
    bool SerializeToFile(const std::string& filename, VariantSerializeType type = VariantSerializeType::Binary, bool jsonFormat = true);
    bool DeserializeFromFile(const std::string& filename, VariantSerializeType type = VariantSerializeType::Binary);
    
    std::string ToJsonString(bool format = false);
    void FromJsonString(const std::string &jsonStr);
    std::vector<uint8_t> ToBinaryString();
    void FromBinaryString(const std::vector<uint8_t> &binaryStr);

    using SerializeFunc = std::function<void(const std::any&, uint8_t* buffer, size_t offset)>;
    using DeserializeFunc = std::function<std::any(const uint8_t* buffer, size_t offset)>;
    struct SerializeStruct
    {
        SerializeFunc   serialize;
        DeserializeFunc deserialize;
        size_t          sesize;
    };

    template <typename T>
    /**
     * @description: 注册用户自定义序列化
     * @return {*}
     * @Author: dengzhijun
     * @Date: 2025-01-17 10:21:41
     * @LastEditTime: Do not edit
     * @LastEditors: dengzhijun
     * 
     * 演示
     * struct Point{ int x; int y; }
     *
     *   // 序列化函数 这种方式，必须是标准的内存排列结构
     *   static void Serialize(const std::any& data, uint8_t* buffer, size_t& offset)
     *   {
     *      const Point& point = std::any_cast<const Point&>(data);
     *      std::memcpy(buffer + offset, &point, sizeof(point));
     *      offset += sizeof(point);
     *   }
     *
     *   // 反序列化函数
     *   static std::any Deserialize(const uint8_t* buffer, size_t& offset)
     *   {
     *       Point point;
     *       std::memcpy(&point, buffer + offset, sizeof(point));
     *       offset += sizeof(point);
     *       return point;
     *   }
     *
        static void Serialize(const std::any& data, uint8_t* buffer, size_t& offset)
        {
            const Point& point = std::any_cast<const Point&>(data);

            float x_be = ToBigEndian(point.x);
            float y_be = ToBigEndian(point.y);

            std::memcpy(buffer + offset, &x_be, sizeof(x_be));
            offset += sizeof(x_be);

            std::memcpy(buffer + offset, &y_be, sizeof(y_be));
            offset += sizeof(y_be);
        }

        static std::any Deserialize(const uint8_t* buffer, size_t& offset)
        {
            float x_be, y_be;

            std::memcpy(&x_be, buffer + offset, sizeof(x_be));
            offset += sizeof(x_be);
            float x = FromBigEndian(x_be);

            std::memcpy(&y_be, buffer + offset, sizeof(y_be));
            offset += sizeof(y_be);
            float y = FromBigEndian(y_be);

            return std::make_any<Point>(Point{x, y});
        }
     *
     *   序列化函数，反序列化函数，序列化大小
     * @Email: jiqianqiudameng@gmail.com
     * @param {SerializeFunc} serializeFunc
     * @param {DeserializeFunc} deserializeFunc
     */
    static void RegisterType(SerializeFunc serializeFunc, DeserializeFunc deserializeFunc,size_t sesize = sizeof(T))
    {
        std::lock_guard<std::mutex> lock(m_typeRegistryMutex);
        std::string typeName = DemangleTypeName(typeid(T).name());
        m_typeRegistry[typeName].serialize = serializeFunc;
        m_typeRegistry[typeName].deserialize = deserializeFunc;
        m_typeRegistry[typeName].sesize = sesize;
    }

    using SerializeJsonFunc = std::function<void(const std::any&, std::unordered_map<std::string, Variant>&)>;
    using DeserializeJsonFunc = std::function<std::any(std::unordered_map<std::string, Variant>&)>;
    template <typename T>
    /**
     * @description: 注册用户自定义数据需要序列化和反序列化到json
     * @return {*}
     * @Author: dengzhijun
     * @Date: 2025-01-17 10:21:57
     * @LastEditTime: Do not edit
     * @LastEditors: dengzhijun
     * 
     * 演示
     * struct Point{ int x; int y; Point(int x, int y):x(x), y(y){} }
     * 
     *   // 序列化json函数
     *   static void SerializeJson(const std::any& data,VariantHash& variant)
     *   {
     *       const Point& point = std::any_cast<const Point&>(data);
     *       variant["x"] = point.x;
     *       variant["y"] = point.y;
     *   }
     *
     *   // 反序列化json函数
     *   static std::any DeserializeJson(VariantHash& variant)
     *   {
     *       Point point(variant["x"], variant["y"]);
     *       return point;
     *   }
     * 
     *   Variant::RegisterJsonType<Point>(Point::SerializeJson, Point::DeserializeJson);
     * @Email: jiqianqiudameng@gmail.com
     * @param {SerializeJsonFunc} serializeFunc
     * @param {DeserializeJsonFunc} deserializeFunc
     */
    static void RegisterJsonType(SerializeJsonFunc serializeFunc, DeserializeJsonFunc deserializeFunc)
    {
        std::lock_guard<std::mutex> lock(m_typeRegistryMutex);
        std::string typeName = DemangleTypeName(typeid(T).name());
        m_jsonTypeRegistry[typeName] = {serializeFunc, deserializeFunc};
    }

private:
    struct VariantPrivate;

    template <VariantType VT>
    struct BinarySerializer
    {
        using NativeType = typename VariantTypeTraits<VT>::Type;
        static void serialize(const VariantPrivate& priv, uint8_t* buffer, size_t& offset)
        {
            NativeType value = std::any_cast<NativeType>(priv.m_data);
            NativeType be_value = ToBigEndian(value);
            std::memcpy(buffer + offset, &be_value, sizeof(be_value));
            offset += sizeof(be_value);
        }
    };

    template <VariantType VT>
    struct BinaryDeSerializer
    {
        using NativeType = typename VariantTypeTraits<VT>::Type;
        static void deserialize(VariantPrivate& priv, const uint8_t* buffer, size_t& offset)
        {
            NativeType value;
            std::memcpy(&value, buffer + offset, sizeof(value));
            offset += sizeof(value);
            priv.m_data = std::move(FromBigEndian(value));
        }
    };

    template <typename Container>
    void SerializerJsonSequence(const Container& container, std::ostream& os, bool format, int depth) const
    {
        os << "[";
        if (format && !container.empty())
        {
            os << "\n";
            int childDepth = depth + 1;
            bool first = true;
            for (const auto& item : container)
            {
                if (!first) os << ",\n";
                Indent(os, childDepth);
                item.SerializeJson(os, format, childDepth);
                first = false;
            }
            os << "\n";
            Indent(os, depth);
        }
        else
        {
            bool first = true;
            for (const auto& item : container)
            {
                if (!first) os << ",";
                item.SerializeJson(os, format, depth + 1);
                first = false;
            }
        }
        os << "]";
    }

    template<typename MapContainer>
    void SerializeJsonMap(const MapContainer& map, std::ostream& os, bool format, int depth) const
    {
        os << "{";
        if (format && !map.empty())
        {
            os << "\n";
            int childDepth = depth + 1;
            bool first = true;
            for (const auto& pair : map)
            {
                if (!first) os << ",\n";
                Indent(os, childDepth);
                os << "\"" << pair.first << "\":";
                if (format) os << " ";
                pair.second.SerializeJson(os, format, childDepth);
                first = false;
            }
            os << "\n";
            Indent(os, depth);
        }
        else
        {
            bool first = true;
            for (const auto& pair : map)
            {
                if (!first) os << ",";
                os << "\"" << pair.first << "\":";
                pair.second.SerializeJson(os, format, depth + 1);
                first = false;
            }
        }
        os << "}";
    }

    inline size_t CalculateBinarySize() const;
    inline void SerializeToBuffer(uint8_t* buffer, size_t& offset) const;
    inline void DeserializeFromBuffer(const uint8_t* buffer, size_t& offset);

    inline void SerializeJson(std::ostream& os, bool format = false, int depth = 0) const;
    inline void DeserializeJson(const char*& ptr, const char* end);

    inline const char* SkipWhitespace(const char* ptr, const char* end);
    inline const char* ParseJsonString(const char* ptr, const char* end, std::string& out);
    inline const char* ParseJsonNumber(const char* ptr, const char* end, Variant& out);

    inline void Indent(std::ostream& os, int depth) const;
    struct VariantPrivate
    {
        VariantPrivate(VariantType type = VariantType::None)
            : m_type(type)
        {
        }

        VariantPrivate(VariantType type, const std::any &data, const std::string &name = "")
            : m_data(data)
            , m_type(type)
            , m_typeName(name)
        {
        }

        VariantPrivate(VariantType type, std::any &&data, const std::string &name = "")
            :  m_data(std::move(data))
            , m_type(type)
            , m_typeName(name)
        {
        }

        VariantPrivate(const VariantPrivate &data)
            : m_data(data.m_data)
            , m_type(data.m_type)
            , m_typeName(data.m_typeName)
        {
        }

        VariantPrivate(VariantPrivate &&data) noexcept
            : m_data(std::move(data.m_data))
            , m_type(std::move(data.m_type))
            , m_typeName(std::move(data.m_typeName))
        {
        }

        std::any m_data;
        VariantType m_type = VariantType::None;
        std::string m_typeName = "";
    };
    std::unique_ptr<VariantPrivate> m_private;
    static std::unordered_map<std::string, SerializeStruct> m_typeRegistry;
    static std::unordered_map<std::string, std::pair<SerializeJsonFunc, DeserializeJsonFunc>> m_jsonTypeRegistry;
    static std::mutex m_typeRegistryMutex;
};

template <typename T>
/**
 * @description: 取特定类型的值，没有回返回默认值
 * @return {取值类型}
 * @Author: dengzhijun
 * @Date: 2025-01-17 10:28:59
 * @LastEditTime: Do not edit
 * @LastEditors: dengzhijun
 * @Email: jiqianqiudameng@gmail.com
 */
inline T Variant::Value() const
{
    if (m_private == nullptr)
    {
        throw std::runtime_error("数据为空，不能取值.");
    }

    if (!m_private->m_data.has_value())
    {
        return T();
    }

    switch (m_private->m_type)
    {
    case VariantType::Bool:
        return ConvertValue<T>(std::any_cast<bool>(m_private->m_data));
    case VariantType::Int:
        return ConvertValue<T>(std::any_cast<int>(m_private->m_data));
    case VariantType::UInt:
        return ConvertValue<T>(std::any_cast<unsigned int>(m_private->m_data));
    case VariantType::Long:
        return ConvertValue<T>(std::any_cast<long long>(m_private->m_data));
    case VariantType::ULong:
        return ConvertValue<T>(std::any_cast<unsigned long long>(m_private->m_data));
    case VariantType::Float:
        return ConvertValue<T>(std::any_cast<float>(m_private->m_data));
    case VariantType::Double:
        return ConvertValue<T>(std::any_cast<double>(m_private->m_data));
    case VariantType::String:
        return ConvertValue<T>(std::any_cast<std::string>(m_private->m_data));
    default:
        try
        {
            return std::any_cast<T>(m_private->m_data);
        }
        catch (const std::bad_any_cast&)
        {
            std::cerr << "转成指定类似失败.";
            return T();
        }
    }
}

template <typename T, typename U>
inline T Variant::ConvertValue(const U &value) const
{
    if constexpr (std::is_same_v<T, U>)
    {
        return value;
    }
    else if constexpr (std::is_arithmetic_v<T> && std::is_arithmetic_v<U>)
    {
        return static_cast<T>(value);
    }
    else if constexpr (std::is_same_v<T, std::string> && std::is_arithmetic_v<U>)
    {
        return std::to_string(value);
    }
    else if constexpr (std::is_same_v<T, bool> && std::is_arithmetic_v<U>)
    {
        return static_cast<bool>(value);
    }
    else if constexpr (std::is_same_v<T, double> && std::is_same_v<U, std::string>)
    {
        try
        {
            return std::stod(value);
        }
        catch (const std::exception &)
        {
            return 0.0;
        }
    }
    else if constexpr (std::is_same_v<T, int> && std::is_same_v<U, std::string>)
    {
        try
        {
            return std::stoi(value); 
        }
        catch (const std::exception &)
        {
            return 0;
        }
    }
    else
    {
        throw std::runtime_error("不支持的类型转换.");
    }
}

template <typename T>
/**
 * @description: 取特定类型的值引用，没有会报错
 * @return {*}
 * @Author: dengzhijun
 * @Date: 2025-01-17 10:29:42
 * @LastEditTime: Do not edit
 * @LastEditors: dengzhijun
 * @Email: jiqianqiudameng@gmail.com
 */
inline T &Variant::RefValue() const
{
    if (!m_private) 
    {
        throw std::runtime_error("Variant 内部数据未初始化");
    }
    
    if (!m_private->m_data.has_value()) 
    {
        auto non_const_this = const_cast<Variant*>(this);
        *non_const_this = std::move(FromValue<T>(T{}));
    }
    try
    {
        return std::any_cast<T&>(m_private->m_data);
    }
    catch (const std::bad_any_cast &)
    {
        throw std::runtime_error("想访问引用但是类型不对.");
    }
}

template<typename T>
/**
 * @description: 通过任意值转成Variant
 * @return {*}
 * @Author: dengzhijun
 * @Date: 2025-01-17 10:31:49
 * @LastEditTime: Do not edit
 * @LastEditors: dengzhijun
 * @Email: jiqianqiudameng@gmail.com
 */
inline Variant Variant::FromValue(T t)
{
    Variant variant;
    variant.m_private->m_data = std::any(t);
    if constexpr (std::is_same_v<T, bool>)
    {
        variant.m_private->m_type = VariantType::Bool;
    }
    if constexpr (std::is_same_v<T, int>)
    {
        variant.m_private->m_type = VariantType::Int;
    }
    else if constexpr (std::is_same_v<T, unsigned int>)
    {
        variant.m_private->m_type = VariantType::UInt;
    }
    else if constexpr (std::is_same_v<T, long long>)
    {
        variant.m_private->m_type = VariantType::Long;
    }
    else if constexpr (std::is_same_v<T, unsigned long long>)
    {
        variant.m_private->m_type = VariantType::ULong;
    }
    else if constexpr (std::is_same_v<T, float>)
    {
        variant.m_private->m_type = VariantType::Float;
    }
    else if constexpr (std::is_same_v<T, double>)
    {
        variant.m_private->m_type = VariantType::Double;
    }
    else if constexpr (std::is_same_v<T, std::string>)
    {
        variant.m_private->m_type = VariantType::String;
    }
    else if constexpr (std::is_same_v<T, std::list<Variant>>)
    {
        variant.m_private->m_type = VariantType::List;
    }
    else if constexpr (std::is_same_v<T, std::vector<Variant>>)
    {
        variant.m_private->m_type = VariantType::Vector;
    }
    else if constexpr (std::is_same_v<T, std::set<Variant>>)
    {
        variant.m_private->m_type = VariantType::Set;
    }
    else if constexpr (std::is_same_v<T, std::map<std::string, Variant>>)
    {
        variant.m_private->m_type = VariantType::Map;
    }
    else if constexpr (std::is_same_v<T, std::unordered_map<std::string, Variant>>)
    {
        variant.m_private->m_type = VariantType::Hash;
    }
    else if constexpr (std::is_same_v<T, std::vector<uint8_t>>)
    {
        variant.m_private->m_type = VariantType::Binary;
    }
    if constexpr (!std::disjunction_v<
                      std::is_same<T, bool>,
                      std::is_same<T, int>,
                      std::is_same<T, unsigned int>,
                      std::is_same<T, long long>,
                      std::is_same<T, unsigned long long>,
                      std::is_same<T, float>,
                      std::is_same<T, double>,
                      std::is_same<T, std::string>,
                      std::is_same<T, std::list<Variant>>,
                      std::is_same<T, std::vector<Variant>>,
                      std::is_same<T, std::set<Variant>>,
                      std::is_same<T, std::map<std::string, Variant>>,
                      std::is_same<T, std::unordered_map<std::string, Variant>>
                      >)
    {
        variant.m_private->m_type = VariantType::User;
        variant.m_private->m_typeName = DemangleTypeName(typeid(T).name());
    }
    return variant;

    // C++17 引入了强制复制消除（guaranteed copy elision），这意味着在某些情况下，编译器可以直接在目标位置构造对象，而不经过临时对象。
    // 显式使用 std::move 可能会干扰这种优化。
    // return std::move(variant); Moving a temporary object prevents copy elision (fix available)
}
}

// Variant哈希特化
namespace std 
{

template <typename T>
inline size_t hash_combine(const T& val)
{
    return std::hash<T>()(val);
}

template<> struct hash<Tool::Variant> 
{
size_t operator()(const Tool::Variant& v) const
{
    // 基础哈希值从类型枚举开始
    size_t hashVal = hash_combine(static_cast<int>(v.Type()));

    // 每种类型叠加对应的值哈希
    switch (v.Type()) 
    {
    case Tool::VariantType::None:
        hashVal += 12345; // 固定值
        break;

    case Tool::VariantType::Bool:
        hashVal += hash_combine(v.ToBool()) * 31;
        break;

    case Tool::VariantType::Int:    hashVal += hash_combine(v.ToInt()) * 31; break;
    case Tool::VariantType::UInt:   hashVal += hash_combine(v.ToUInt()) * 31; break;
    case Tool::VariantType::Long:   hashVal += hash_combine(v.ToLong()) * 31; break;
    case Tool::VariantType::ULong:  hashVal += hash_combine(v.ToULong()) * 31; break;
    case Tool::VariantType::Float:  hashVal += hash_combine(v.ToFloat()) * 31; break;
    case Tool::VariantType::Double: hashVal += hash_combine(v.ToDouble()) * 31; break;
    case Tool::VariantType::String: hashVal += hash_combine(v.ToString()) * 31; break;
    case Tool::VariantType::Vector:
    {
        auto& vec = v.RefValue<Tool::VariantVector>();
        for (const auto& elem : vec)
        {
            hashVal += hash_combine(elem) * 17;
        }
        break;
    }
    case Tool::VariantType::List:
    {
        auto& list = v.RefValue<Tool::VariantList>();
        for (const auto& elem : list)
        {
            hashVal += hash_combine(elem) * 17;
        }
        break;
    }
    case Tool::VariantType::Set:
    {
        auto& set = v.RefValue<Tool::VariantSet>();
        for (const auto& elem : set)
        {
            hashVal += hash_combine(elem) * 19;
        }
        break;
    }
    case Tool::VariantType::Map:
    {
        auto& map = v.RefValue<Tool::VariantMap>();
        for (const auto& pair : map) {
            hashVal += hash_combine(pair.first) * 23 + hash_combine(pair.second) * 29;
        }
        break;
    }
    case Tool::VariantType::Hash:
    {
        auto& hash = v.RefValue<Tool::VariantHash>();
        for (const auto& pair : hash)
        {
            hashVal += hash_combine(pair.first) * 23 + hash_combine(pair.second) * 29;
        }
        break;
    }

    case Tool::VariantType::Binary:
    {
        auto& bin = v.RefValue<std::vector<uint8_t>>();
        for (uint8_t b : bin)
        {
            hashVal += hash_combine(b) * 37;
        }
        break;
    }

    case Tool::VariantType::User:
        hashVal += 54321; // 固定值
        break;
    }
    return hashVal;
}

};

}
#endif // TOOL_VARIANT_H
